// 路由白名单
const allowNoMatchPaths = ['/healthcheck', '/favicon.ico']

module.exports = async (ctx, next) => {
  await next()
  // SPA应用配置
  if (ctx.status === 404 && !ctx.path.startsWith('/api')) {
    ctx.redirect('/front_dist') // 前端路由接管
    return
  }

  if (ctx.status === 404 && !ctx.body && !allowNoMatchPaths.includes(ctx.path)) {
    ctx.body = {
      success: false,
      error: {
        code: 404,
        method: ctx.method,
        message: `路由未匹配: ${ctx.method} ${ctx.path}`,
        path: ctx.path,
        timestamp: new Date().toLocaleString(),
      },
    }
    // 记录警告日志
    ctx.app.emit('routeWarn', {
      message: '未匹配的路由请求',
      ctx,
    })
  }
}
